//
//  HomeViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/29.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON
class HomeViewController: RootViewController ,UITableViewDelegate,UITableViewDataSource, BottomShadow{
    
    @IBOutlet weak var mainScrollView: UIScrollView!
    lazy var tableview:UITableView = UITableView()
    lazy var videoTableview:UITableView = UITableView()
    var data:[ArticleModel] = []
    var videoData:[VideoModel] = []
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    // 顶部刷新
    let videoHeader = MJRefreshNormalHeader()
    // 底部刷新
    let videoFooter = MJRefreshAutoNormalFooter()
    var page:Int = 0
    var totalPage:Int = 0
    var rightSelect = false
    
    var indexPath :IndexPath?
    
    let bannerHeight: CGFloat = 211
    let pageControlHeight: CGFloat = 25
    let consultationHeight: CGFloat = 125
    lazy var bannerView: FSPagerView = {

        let bannerView = FSPagerView()
        bannerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeight(r: ConsultationViewController.bannerHeight))
        bannerView.delegate = self
        bannerView.dataSource = self
        bannerView.isInfinite = true
        bannerView.automaticSlidingInterval = 3.0
        bannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        return bannerView
    }()
    lazy var pageControl: FSPageControl = {
        let pageControl = FSPageControl()
        pageControl.frame = CGRect(x: 0, y: bannerView.height - ConsultationViewController.pageControlHeight, width: bannerView.width, height: ConsultationViewController.pageControlHeight)
        pageControl.numberOfPages = bannerData.count
        pageControl.contentHorizontalAlignment = .center
        pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        pageControl.setFillColor(.gray, for: .normal)
        pageControl.setFillColor(.white, for: .selected)
        pageControl.setPath(UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 0, width: 5, height: 5),                 cornerRadius: 2.5), for: .normal)
        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 5, height: 5)), for: .selected)
        pageControl.itemSpacing = 8
        return pageControl
    }()
    var bannerData:[BannerModel] = []
    
    lazy var videoBannerView: FSPagerView = {
        let videoBannerView = FSPagerView()
        videoBannerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeight(r: ConsultationViewController.bannerHeight))
        videoBannerView.delegate = self
        videoBannerView.dataSource = self
        videoBannerView.isInfinite = true
        videoBannerView.automaticSlidingInterval = 3.0
        videoBannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        return videoBannerView
        
    }()
    lazy var videoPageControl: FSPageControl = {
        let videoPageControl = FSPageControl()
        videoPageControl.frame = CGRect(x: 0, y: videoBannerView.height - ConsultationViewController.pageControlHeight, width: videoBannerView.width, height: ConsultationViewController.pageControlHeight)
        videoPageControl.numberOfPages = videoBannerData.count
        videoPageControl.contentHorizontalAlignment = .center
        videoPageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        videoPageControl.setFillColor(.gray, for: .normal)
        videoPageControl.setFillColor(.white, for: .selected)
        videoPageControl.setPath(UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 0, width: 5, height: 5),                 cornerRadius: 2.5), for: .normal)
        videoPageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 5, height: 5)), for: .selected)
        videoPageControl.itemSpacing = 8
        return videoPageControl
    }()
    var videoBannerData:[BannerModel] = []
    
    let notiName:String = "HomeReloadCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        setNavigationColor(colorState: .black)
        setTitleView()
        initTableView()
        initVideoTableView()
        NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name:NSNotification.Name(rawValue: notiName), object: nil)
    }
    
    @objc private func notificationAction(noti: Notification) {
        if noti.object == nil {
            return
        }
        if indexPath != nil {
            if noti.object is VideoModel {
                self.videoData[(self.indexPath?.row)!] = noti.object as! VideoModel
                self.videoTableview.reloadRows(at: [self.indexPath!], with: UITableViewRowAnimation.automatic)
            }else {
                self.data[(self.indexPath?.row)!] = noti.object as! ArticleModel
                self.tableview.reloadRows(at: [self.indexPath!], with: UITableViewRowAnimation.automatic)
            }
        }
        
    }
    
    func setUI() {
        
//        let consultationVC = ConsultationViewController(nibName: "\(ConsultationViewController.self)", bundle: nil, vcType: .news)
//        let videoVC = ConsultationViewController(nibName: "\(ConsultationViewController.self)", bundle: nil, vcType: .video)
//        self.addChildViewController(consultationVC)
//        self.addChildViewController(videoVC)
//        for (index, vc) in self.childViewControllers.enumerated() {
//            vc.view.frame = CGRect(x: CGFloat(index) * ScreenWidth, y: 0, width: mainScrollView.width, height: mainScrollView.height)
//            mainScrollView.addSubview(vc.view)
            
//        }
        mainScrollView.contentSize = CGSize(width: ScreenWidth * 2, height: mainScrollView.frame.size.height)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if rightSelect{
            return videoData.count
        }
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "\(ConsultaionTableViewCell.self)", for: indexPath) as? ConsultaionTableViewCell
        if rightSelect {
            cell?.showVideoData(model: videoData[indexPath.row])
        }
        else
        {
            cell?.showConsultaionData(model: data[indexPath.row])
        }
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 260
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 2.5
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 2.5
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.indexPath = indexPath
        if rightSelect {
            let vc = VideoDetailViewController(nibName: ("\(VideoDetailViewController.self)"), bundle: nil, type: HomeVCSelect.video)
            vc.model = videoData[indexPath.row]
            vc.notiName = self.notiName
            self.navigationController?.pushViewController(vc, animated: true)
        }
        else{
            let vc = ConsultationDetailViewController(nibName: ("\(ConsultationDetailViewController.self)"), bundle: nil, type: HomeVCSelect.news)
            vc.model = data[indexPath.row]
            vc.notiName = self.notiName
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    func initTableView() {
        tableview.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight - 110)
        
        tableview.delegate = self
        tableview.dataSource = self
        tableview.backgroundColor = UIColor.clear
        tableview.register(UINib(nibName: "\(ConsultaionTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(ConsultaionTableViewCell.self)")
        tableview.tableHeaderView = setBannerData()

        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        tableview.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        tableview.reloadData()

        mainScrollView.addSubview(tableview)
        self.headerRefresh()
    }
    func initVideoTableView() {
        videoTableview.frame = CGRect(x: ScreenWidth, y: 0, width: ScreenWidth, height: ScreenHeight - 110)
        
        videoTableview.delegate = self
        videoTableview.dataSource = self
        videoTableview.backgroundColor = UIColor.clear
        videoTableview.register(UINib(nibName: "\(ConsultaionTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(ConsultaionTableViewCell.self)")
        videoTableview.tableHeaderView = setVideoBannerData()
        let headerAction:Selector = #selector(headerRefresh)
        videoHeader.setRefreshingTarget(self, refreshingAction: headerAction)
        videoTableview.mj_header = videoHeader
        let footerAction:Selector = #selector(footerRefresh)
        videoFooter.setRefreshingTarget(self, refreshingAction: footerAction)
        videoTableview.reloadData()
        
        mainScrollView.addSubview(videoTableview)
    }

    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()
        if rightSelect {
            self.fetchBannerList(type: 2)
        }
        else{
            self.fetchBannerList(type: 1)
        }
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        if rightSelect {
            self.fetchVideoList(parameters: ["page":page,"pageSize":10,"type":1,"ascription":"video"])
        }
        else{
            self.fetchArticleList(parameters: ["page":page,"pageSize":10,"type":1])
        }
    }
}

extension HomeViewController :FSPagerViewDelegate, FSPagerViewDataSource{
    
    // MARK: - TitleView
    func setTitleView() {
        let titleView = UIView()
        let leftImage = UIImage(named: "home_title_text")
        let buttonSize: CGFloat = 22.0
        guard let image = leftImage else {
            assert(false, "图片不存在！")
            return
        }
        
        titleView.frame = CGRect(x: 0, y: 0, width: 47.5 + image.size.width * 2.0, height: 44)
        let leftButton = UIButton(type: .custom)
        leftButton.setImage(leftImage, for: .normal)
        leftButton.setImage(UIImage(named: "home_title_text_select"), for: .selected)
        leftButton.tag = 1
        leftButton.frame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
        leftButton.center = CGPoint(x: leftButton.centerX, y: 22)
        leftButton.addTarget(self, action: #selector(leftButtonTap(_ :)), for: .touchUpInside)
        leftButton.isSelected = true
        titleView.addSubview(leftButton)
        
        let rightButton = UIButton(type: .custom)
        rightButton.setImage(UIImage(named: "home_title_video"), for: .normal)
        rightButton.tag = 2
        rightButton.setImage(UIImage(named: "home_title_video_select"), for: .selected)
        rightButton.addTarget(self, action: #selector(rightButtonTap(_ :)), for: .touchUpInside)
        rightButton.frame = CGRect(x: titleView.width - image.size.width, y: 0, width: buttonSize, height: buttonSize)
        rightButton.center = CGPoint(x: rightButton.centerX, y: 22)
        titleView.addSubview(rightButton)
        
        self.navigationItem.titleView = titleView
    }
    
    @objc func leftButtonTap(_ btn:UIButton) {
        self.rightSelect = false
        btn.isSelected = true
        let y = videoTableview.contentOffset.y
        videoTableview.setContentOffset(CGPoint(x: 0, y: y), animated: true)
        setTitleButtonStatus(btn: btn)
        mainScrollView.setContentOffset(.zero, animated: true)
    }
    
    @objc func rightButtonTap(_ btn:UIButton) {
        self.rightSelect = true
        btn.isSelected = true
        let y = tableview.contentOffset.y
        tableview.setContentOffset(CGPoint(x: 0, y: y), animated: true)
        setTitleButtonStatus(btn: btn)
        mainScrollView.setContentOffset(CGPoint(x: ScreenWidth, y: 0), animated: true)
        if videoBannerData.count == 0 {//没有数据才请求加载，否则要加载只能下拉刷新
            self.videoTableview.mj_header.beginRefreshing()
        }
    }
    
    func setTitleButtonStatus(btn: UIButton) {
        if let views = navigationItem.titleView?.subviews {
            for item in views {
                if !item.isEqual(btn) {
                    let button = item as? UIButton
                    button?.isSelected = false
                }
            }
        }
    }
    
    /// 获取文章列表
    func fetchArticleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(homeArticleUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.data.removeAll()
                                            self.tableview.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.tableview.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = ArticleModel(fromDic: dic)
                                            
                                            let labels = dic["labels"]?.array!
                                            
                                            model.initLabels(arr: labels!)
                                            
                                            let label = dic["label"]
                                            if !(label?.isEmpty)!{
                                                model.initLabel(dic: (label?.dictionary!)!)
                                            }
                                            let author = dic["author"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            let grade = dic["author"]!["grade"]
                                            if !grade.isEmpty{
                                                model.author?.initGrade(dic: (grade.dictionary!))
                                            }
                                            let channel = dic["channel"]
                                            if !(channel?.isEmpty)!{
                                                model.initChannel(dic: (channel?.dictionary!)!)
                                            }
                                            
                                            self.data.append(model)
                                        }
                                        if self.totalPage == self.data.count{
                                            self.tableview.mj_footer = nil
                                        }
                                        else{
                                            self.tableview.mj_footer = self.footer
                                        }
                                        self.tableview.reloadData()
                                    }
                                    else{
                                        if self.page == 1{
                                            self.tableview.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.tableview.mj_footer.endRefreshing()
                                        }

                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.tableview.mj_header.endRefreshing()
                                }
                                else{
                                    self.tableview.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }

    }
    
    
    /// 获取视频列表
    func fetchVideoList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(homeVideoUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page == 1{
                                            self.videoData.removeAll()
                                            self.videoTableview.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.videoTableview.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            var model = VideoModel(fromDic: dic)
                                            let labels = dic["labels"]?.array!
                                            
                                            model.initLabels(arr: labels!)

                                            let label = dic["label"]
                                            if !(label?.isEmpty)!{
                                                model.initLabel(dic: (label?.dictionary!)!)
                                            }
                                            let author = dic["author"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            let grade = dic["author"]!["grade"]
                                            if !grade.isEmpty{
                                                model.author?.initGrade(dic: (grade.dictionary!))
                                            }
                                            let channel = dic["channel"]
                                            if !(channel?.isEmpty)!{
                                                model.initChannel(dic: (channel?.dictionary!)!)
                                            }
                                            
                                            self.videoData.append(model)
                                        }
                                        if self.totalPage == self.videoData.count{
                                            self.videoTableview.mj_footer=nil
                                        }
                                        else{
                                            self.videoTableview.mj_footer = self.videoFooter
                                        }
                                        self.videoTableview.reloadData()
                                    }
                                    else{
                                        if self.page == 1{
                                            self.videoTableview.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.videoTableview.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.videoTableview.mj_header.endRefreshing()
                                }
                                else{
                                    self.videoTableview.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 获取banner数据
    func fetchBannerList(type:Int) -> Void {
        let requesturl = "\(BaseURL)\(bannerUlr)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: ["type":type] ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let arr = json["data"].array!
                                        
                                        if type == 1{
                                            self.bannerData.removeAll()
                                        }
                                        else if type == 2{
                                            self.videoBannerData.removeAll()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = BannerModel(fromDic: dic)
                                            if type == 1{
                                                self.bannerData.append(model)
                                            }
                                            else if type == 2{
                                                self.videoBannerData.append(model)
                                            }
                                        }
                                        if type == 1{
                                            self.pageControl.numberOfPages = self.bannerData.count
                                            self.bannerView.reloadData()
                                        }
                                        else if type == 2{
                                            self.videoPageControl.numberOfPages = self.videoBannerData.count
                                            self.videoBannerView.reloadData()
                                        }
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    func setBannerData() -> UIView {
        
        let mainView = UIView()
        var rect = bannerView.frame
        rect.size.height += 10
        mainView.frame = rect
        mainView.backgroundColor = ONColor.cellBGColor
        mainView.addSubview(bannerView)
        mainView.addSubview(pageControl)
        
        setShadow(view: bannerView, opacity: 0.5, size: bottomShadowOffset, color: UIColor.black, cornerradius: 0)
        return mainView
    }
    
    func setVideoBannerData() -> UIView {
        
        let mainView = UIView()
        var rect = videoBannerView.frame
        rect.size.height += 10
        mainView.frame = rect
        mainView.backgroundColor = ONColor.cellBGColor
        mainView.addSubview(videoBannerView)
        mainView.addSubview(videoPageControl)
        
        setShadow(view: videoBannerView, opacity: 0.5, size: bottomShadowOffset, color: UIColor.black, cornerradius: 0)
        
        return mainView
    }

    // MARK:- FSPagerView DataSource
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        if pagerView == self.bannerView {
            return self.bannerData.count
        }
        return self.videoBannerData.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.isDescribeLabel = true
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.clipsToBounds = true
        cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
        if pagerView == self.bannerView {
            let model = self.bannerData[index]
            if let cpath = model.image{
                let path:String = "\(BaseURL)\(cpath)"
                
                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                
                cell.imageView?.sd_setImage(with: url! as URL, completed: nil)

            }
            if let name = model.title{
                cell.textLabel?.text = name
            }
        }
        else{
            let model = self.videoBannerData[index]
            if let cpath = model.image{
                let path:String = "\(BaseURL)\(cpath)"
                
                let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
                
                cell.imageView?.sd_setImage(with: url! as URL, completed: nil)
                
            }
            if let name = model.title{
                cell.textLabel?.text = name
            }
        }
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        if rightSelect{
            let model = self.videoBannerData[index]
            bannerJump(model: model)
        }else {
            let model = self.bannerData[index]
            bannerJump(model: model)
        }
        
        
        if pagerView == self.bannerView {
            self.pageControl.currentPage = index
        }
        else{
            self.videoPageControl.currentPage = index
        }
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {

        if pagerView == self.bannerView {
            guard self.pageControl.currentPage != pagerView.currentIndex else {
                return
            }
            self.pageControl.currentPage = pagerView.currentIndex
        }
        else{
            guard self.videoPageControl.currentPage != pagerView.currentIndex else {
                return
            }
            self.videoPageControl.currentPage = pagerView.currentIndex
        }
    }
    
}
